package objectRank;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;

import my.facebook.GraphExample;

import com.restfb.types.Group;

import edu.fiu.cis.personalize.shared.GoogleDocument;


/**
 *
 * @author Reza
 */
public class GraphBean implements Serializable{
    String API_KEY = "60683cb18b1ce814835d081ab35c580e";
    String APP_SECRET = "14142932f401caac22391cfd8b1e5a2c";
    String APP_ID = "198452336852498";
    String REDIRECT_URL = "http://localhost:8080/MyGroups/";
    String my_URL = "https://www.facebook.com/dialog/oauth?client_id=" + APP_ID + "&redirect_uri=" + REDIRECT_URL + "&scope=email,offline_access";
    String accessToken = "2227470867|2.y4fyuxakiHJHoLfzlirN3Q__.3600.1304535600.0-597296639|sGU4GpoJGYf2veq5tQKqr8la_0c";
    //String accessToken = "198452336852498|1112645c33fabd1f04da4afd-597296639|Mh2Rvu_-tbqvQrGwyqvnVOEDzNM";

    String query;
    String user;
    String document;
    HashMap<Node, Double> graphRanks;
    LinkedList<GoogleDocument> googleDocuments;
    LinkedHashMap<GoogleDocument, Double> finalOutput;
    QueryGraph queryGraph;
    ObjectOutputStream objectOut = null;
    File file1;

    
    public GraphBean(){
        this.query = null;
        this.document = null;
        this.graphRanks = new HashMap<Node, Double>();
        this.googleDocuments = new LinkedList<GoogleDocument>();
        this.finalOutput = new LinkedHashMap<GoogleDocument, Double>();

        GraphExample facebookGraph = new GraphExample(accessToken);
        List<Group> groups = facebookGraph.fqlGroups();
        Iterator<Group> itr = groups.iterator();
        HashSet<String> newGroups = new HashSet<String>();
        String ttt;
        //System.out.println("groups in facebook are " + groups.size());
        while(itr.hasNext()){
            ttt = ">>group>> ".concat(itr.next().getDescription());
            newGroups.add(ttt);
            //System.out.println(ttt);
        }
        //Long uid = facebookGraph.getUserId();
        user = ">>user>> ".concat(facebookGraph.fqlUserName());
        System.out.println(user);
        file1 = new File("C:\\Users\\Reza\\Documents\\NetBeansProjects\\MyGroups"
                            + "\\src\\java\\objectRank\\test.bin");
        ObjectInputStream objectIn = null;
        try{
            objectIn = new ObjectInputStream(new BufferedInputStream(
                       new FileInputStream(file1)));
            queryGraph = (QueryGraph)objectIn.readObject();
            Iterator<String> itr1 = newGroups.iterator();
            while(itr1.hasNext()){
                queryGraph.addEdge(itr1.next(), user);
            }
        } catch(ClassNotFoundException e) {
            e.printStackTrace(System.err);
            System.exit(1);
        }catch(IOException e){
            System.err.println("Error in reading file: " + e);
        }

        try {
            objectIn.close(); // Close the input stream
            //file1.delete(); // Delete the file to write the updated QueryObject again
            //file1.createNewFile();
            //objectOut = new ObjectOutputStream(new BufferedOutputStream(
            //            new FileOutputStream(file1)));
            //objectOut.writeObject(queryGraph);
            //objectOut.close(); // Close the output stream
        }catch(IOException e) {
            e.printStackTrace(System.err);
            System.exit(1);
        }
    }

    public void querySubmitted(String query){
        this.query = ">>query>> ".concat(query);
        queryGraph.addEdge(user, this.query);
        queryGraph.addEdge(this.query, user);
        System.out.println("query <-> user edges are added.");
    }

    public void addGoogleDocs(String[] documents, String[] titles){
        GoogleDocument doc;
        System.out.println(documents.length + "," + documents.length +
                "," + documents.length + " are being added.");
        if (documents.length != titles.length){
            for(int i = 0 ; i < documents.length-1 ; i++){
                doc = new GoogleDocument(documents[i], titles[i]);
                googleDocuments.add(doc);
            }
        }else{
            for(int i = 0 ; i < documents.length ; i++){
                doc = new GoogleDocument(documents[i], titles[i]);
                googleDocuments.add(doc);
            }
        }
        
        System.out.println("google docs are added.");
    }

    public void documentClicked(String query, String document){
        queryGraph.addEdge(user, ">>document>>".concat(document));
        queryGraph.addEdge(">>document>>".concat(document), user);
        Integer docId = queryGraph.documentToIdentifyer(document);
        Document doc = queryGraph.identifyerToDocument(docId);
        Integer queryId = queryGraph.queryToIdentifyer(query);
        Query q = queryGraph.identifyerToQuery(queryId);
        Integer numClicks = doc.clickedAfterQuery.get(queryId);
        doc.clickedAfterQuery.put(queryId, (numClicks == null) ? 1 : numClicks + 1);
    }

    public void calculateRank(String query){
        int queryId = queryGraph.queryToIdentifyer(query);
        Query tempQ = queryGraph.identifyerToQuery(queryId);
        queryGraph.calculateRootSet(tempQ);
        queryGraph.calculateBaseSet();
        graphRanks = queryGraph.calculateObjectRank();
        System.out.println("rank is calculated.");
   }

   public void integrateWithGoogle(){
       finalOutput = queryGraph.integrateWithGoogle(graphRanks, googleDocuments);
       System.out.println("integrated with google.");
   }

   public String showOutput(){
       String resultHTML = "<div>";
       Iterator<GoogleDocument> itr = finalOutput.keySet().iterator();
       GoogleDocument temp;
       int count = 0;
       while(itr.hasNext() && count < 20){
               temp = itr.next();
               count++;
               resultHTML += "<a href=\"" + temp.getURL() + "\" target=\"_blank\"" +
			"onclick=\"alert();\"><b>" +
			temp.getTitle() + "</b></a><br/><div/>";
       }
       
       return resultHTML;
   }
}
